import React, { useState, useRef } from 'react';
import { history, connect } from 'umi';
import { Card, Button, Form } from 'antd';
import { Col, Row, Tag, Tooltip, Space } from 'antd';
import DrawerCondition from '@/components/DrawerCondition';
import FormCondition from '@/components/FormCondition';
import Uploadjs from '@/utils/aliOssUpload';
import { stage_tab } from '@/common/contact';
import SelectTagFrom from '@/components/SelectTagForm';
import GoodsSelectComponents from '@/components/OverviewFormSet/components/GoodsSelectComponents';
import { useEffect } from 'react';
import moment from 'moment'
import { dateDisabled } from '@/common/regular'
import PreApplition from './components/PreApplition';
const CodeInfo = (props) => {
  const { dispatch, visible = {}, onClose, handleCallback, loading, searchLoading } = props;
  const { location } = history;
  const { query } = location;
  const { keywordId, spiderUserId } = query;
  const { show = false, detail = {} } = visible;
  const [tagList, setTagList] = useState([])
  const [intentionDirectionList, setintentionDirectionList] = useState([])
  const [targetCourseList, setTargetCourse] = useState([])
  const [intentionCourseList, setIntentionCourseList] = useState([])
  const [schoolList, setSchoolList] = useState([])
  const [specialtyList, setSpecialtyList] = useState([])
  const [tagVisible, setTagVisible] = useState(false);
  const { id, tags = '', tagIds = '', preApplyList = [], canHandlePreApplyInfoFlag = '1' } = detail;
  const [form] = Form.useForm();
  const preRef = useRef(null);
  const { commentId, douyinUserId, accountId, accountItemId, videoId, targetCourseGoodsList = [], intentionCourseGoodsList = [] } = detail;
  useEffect(() => {
    if (!show) {
      setTagList([])
      setintentionDirectionList([])

    }
    else {
      fetchintentionDirectionList()
      fetchListSchool()
      fetchListSpecialty()
      if (tagIds.length) {
        const listId = tagIds.split(',').reverse();
        const listName = tags.split(',')
        setTagList(listId.map((item, index) => {
          return {
            id: Number(item),
            tagName: listName[index]
          }
        }))
      }
      setTargetCourse(targetCourseGoodsList)
      setIntentionCourseList(intentionCourseGoodsList)

    }
  }, [show])
  const fetchintentionDirectionList = () => {
    dispatch({
      type: 'setting/fetchIntentionCourse',
      payload: {},
      callback: (e) => {
        const { intentionCourseList } = e
        setintentionDirectionList(intentionCourseList)
      }
    });
  }
  const fetchListSchool = () => {
    dispatch({
      type: 'selectionWindow/fetchListSchool',
      payload: {
        page: '1',
        limit: '9999'
      },
      callback: (e) => {
        setSchoolList(e)
      }
    });
  }
  const fetchListSpecialty = () => {
    dispatch({
      type: 'selectionWindow/fetchListSpecialty',
      payload: {
        page: '1',
        limit: '9999'
      },
      callback: (e) => {
        setSpecialtyList(e)
      }
    });
  }
  // 新增修改 传id修改 不传id新增
  const fetchRoleEdit = () => {
    form.validateFields().then(async (values) => {
      const { profile, intentionDirection = [], expectedRegistrationDate } = values;
      const img = (await Uploadjs(profile)) || [];
      dispatch({
        type: 'video/fakeSaveUser',
        payload: {
          commentId,
          douyinUserId,
          accountId,
          accountItemId,
          keywordId,
          spiderUserId,
          videoId,
          ...values,
          tagIds: tagList.map(item => { return item.id }).toString(),
          profile: img.toString(),
          targetCourse: targetCourseList.map(item => { return item.id }).toString(),
          intentionCourses: intentionCourseList.map(item => { return item.id }).toString(),
          expectedRegistrationDate:
            expectedRegistrationDate ? moment(expectedRegistrationDate).format('YYYY-MM-DD') : '',
          intentionDirection: intentionDirection.toString(),
          preApplyList: preRef.current.getPre(),
        },
        callback: () => {
          onClose();
          handleCallback();
        },
      });
    });
  };

  const modalProps = {
    title: `新增用户`,
    visible: show,
    onClose,
    destroyOnClose: true,
    footer: (
      <Button type="primary" loading={loading} onClick={fetchRoleEdit}>
        确定
      </Button>
    ),
  };

  const formItems = [
    {
      label: '姓名',
      name: 'username',
      rules: [{ required: false }],
    },
    {
      label: '性别',
      name: 'gender',
      type: 'radio',
      rules: [{ required: false }],
      select: {
        1: '男',
        2: '女',
      },
    },
    {
      type: 'noForm',
      rules: [{ required: false }],
      formItem: (
        <Row style={{ marginBottom: 24 }}>
          <Col style={{
            textAlign: 'right', paddingRight: 8, display: 'flex',
            alignItems: 'center',
            justifyContent: 'flex-end'
          }} span={6}>
            标签:
          </Col>
          <Col style={{
            border: '1px solid #d9d9d9',
            boxSizing: 'border-box',
            height: 32,
            display: 'flex',
            alignItems: 'center',
            padding: '0 12px',
            borderRadius: 2
          }}
            onClick={() => {
              setTagVisible({
                show: true,
                detail: tagList,
              });
            }}
            className="font_hide"
            span={17}
          >
            {tagList.length === 0 && <div style={{ color: '#b2b2b2' }}>选择标签</div>}
            {
              <Tooltip
                title={tagList.map((item, index) => {
                  return item.tagName + ',';
                })}
              >
                <div className="font_hide">
                  {tagList.map((item, index) => {
                    if (index < tagList.length - 1) {
                      return item.tagName + ',';
                    }
                    return item.tagName

                  })}
                </div>
              </Tooltip>
            }
          </Col>
        </Row>
      ),
    },
    {
      label: '手机',
      rules: [{ required: false }],
      name: 'mobile',
    },
    {
      label: '描述',
      name: 'userDesc',
      rules: [{ required: false }],
      type: 'textArea',
    },
    {
      label: '用户头像',
      name: 'profile',
      type: 'upload',
      rules: [{ required: false }],
      maxFile: 1,
    },
    {
      label: '来源',
      name: 'source',
      type: 'select',
      disabled: id,
      select: {
        douyin: '抖音',
      },
    },
    {
      label: '意向方向',
      name: 'intentionDirection',
      mode: 'multiple',
      type: 'select',
      rules: [{ required: false }],
      fieldNames: { label: 'courseName', value: 'id' },
      select: intentionDirectionList,
    },
    {
      label: '意向',
      name: 'intention',
      type: 'select',
      select: {
        1: '1',
        2: '2',
        3: '3',
        4: '4',
        5: '5',
      },
    },
    // {
    //   type: 'noForm',
    //   formItem: (
    //     <GoodsSelectComponents hasSku={'0'} list={targetCourseList} setList={(e) => { setTargetCourse(e) }}></GoodsSelectComponents>
    //   ),
    // },
    {
      type: 'noForm',
      formItem: (
        <GoodsSelectComponents type='intentionCourse' hasSku={'0'} list={intentionCourseList} setList={(e) => { setIntentionCourseList(e) }}></GoodsSelectComponents>
      ),
    },
    {
      label: '预计报名时间',
      name: 'expectedRegistrationDate',
      type: 'dataPicker',
      disabledDate: dateDisabled,
      rules: [{ required: false }],
      format: 'YYYY-MM-DD',
    },
    {
      label: '学校',
      name: 'schoolId',
      type: 'select',
      rules: [{ required: false }],
      fieldNames: { label: 'schoolName', value: 'id' },
      select: schoolList,
    },
    {
      label: '专业',
      name: 'specialtyId',
      type: 'select',
      rules: [{ required: false }],
      fieldNames: { label: 'specialtyName', value: 'id' },
      select: specialtyList,
    },
    {
      label: '考试年份',
      name: 'examYear',
      type: 'select',
      rules: [{ required: false }],
      select: {
        2023: 2023,
        2024: 2024,
        2025: 2025,
        2026: 2026,
        2027: 2027,
        2028: 2028,
      },
    },
    {
      type: 'noForm',
      formItem: (
        <PreApplition
          disabled={canHandlePreApplyInfoFlag}
          ref={preRef}
          defaultList={preApplyList.length > 0 ? preApplyList.map(item => {
            const { detailPreApplyAdmin, preApplyHelpAdminList, mainAdminId, stage } = item
            return {
              mainAdminList: mainAdminId ? [detailPreApplyAdmin] : [],
              helpAdminIdList: preApplyHelpAdminList,
              label: stage_tab[stage],
              value: stage,
              stage: stage
            }
          }) : [{
            label: '培育',
            value: 'cultivate'
          },
          {
            label: '成交',
            value: 'sells'
          },
          {
            label: '服务',
            value: 'service'
          }]}></PreApplition>
      ),

    }

  ];

  return (
    <>
      <DrawerCondition {...modalProps}>
        <FormCondition form={form} formItems={formItems} initialValues={{ ...detail, source: 'douyin' }}></FormCondition>
      </DrawerCondition>
      <SelectTagFrom
        onSetList={setTagList}
        visible={tagVisible}
        onClose={() => setTagVisible(false)}
      ></SelectTagFrom>
    </>
  );
};
export default connect(({ video, loading }) => ({
  loading: loading.models.video,
}))(CodeInfo);
